package com.example.chat.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.chat.config.WebSocketMessageServer;
import com.example.chat.enums.Code;
import com.example.chat.pojo.dto.MessageDTO;
import com.example.chat.pojo.bo.Message;
import com.example.chat.mapper.MessageMapper;
import com.example.chat.pojo.res.ResModel;
import com.example.chat.service.FriendService;
import com.example.chat.service.MessageService;
import com.example.chat.pojo.vo.MessageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.example.chat.constants.RedisConstants.NEW_MESSAGE_KEY;

@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private FriendService friendService;

    @Resource
    private WebSocketMessageServer webSocketMessageServer;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 线程池，处理给前端推送消息任务
     */
    private static final ExecutorService THREAD_POOL= Executors.newFixedThreadPool(10);

    /**
     * 发送消息
     * @param message
     * @return
     */
    @Transactional
    @Override
    public ResModel sendMessage(Message message) {
        if (ObjectUtil.isNotEmpty(message) && StrUtil.isNotEmpty(message.getToUserId())){
            boolean save = save(message);
            //更新聊天日期及最新消息
            friendService.updateChat(message);
            MessageVO messageVO = messageMapper.getChatMsgById(message);
            //给前端推送消息
            THREAD_POOL.submit(()->{
                webSocketMessageServer.sendMessage(messageVO);
            });
            return ResModel.success(Code.SUCCESS,save);
        }
        return ResModel.error(Code.FAIL);
    }

    /**
     * 查询聊天消息
     * @param message
     * @return
     */
    @Override
    public ResModel getChatMsgList(Message message) {
        List<MessageVO> chatMsgList = messageMapper.getChatMsgList(message);
        redisTemplate.delete(NEW_MESSAGE_KEY + message.getToUserId() + message.getFormUserId());
        return ResModel.success(Code.SUCCESS,chatMsgList);
    }

    /**
     * 修改聊天类型
     * @param message
     * @return
     */
    @Override
    public ResModel updateMsgType(MessageDTO message) {
        ResModel chatType = friendService.updateChatType(message);
        return ResModel.success(Code.SUCCESS,chatType.getData());
    }
}
